package com.gx.wisestone.android.grpc.interceptor.uaa;

import com.gx.wisestone.android.grpc.interceptor.InterceptorConstants;
import com.gx.wisestone.android.grpc.interceptor.WsClientCallListener;
import com.orhanobut.logger.Logger;

import io.grpc.ClientCall;
import io.grpc.ForwardingClientCall;
import io.grpc.Metadata;

public class UAAClientCall<ReqT, RespT> extends ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT> {
    private Provider provider;

    protected UAAClientCall(ClientCall delegate, Provider provider) {
        super(delegate);
        this.provider = provider;
    }

    @Override
    public void start(Listener responseListener, Metadata headers) {
        if (null != provider) {
            String token = provider.token();
            Integer sysTenantNo = provider.sysTenantNo();
            String wsVer = provider.wsVer();
            String appVersion = provider.appVersion();
            if (null != token && token.length() > 0) {
                headers.put(InterceptorConstants.AUTHORIZATION_KEY, InterceptorConstants.BEARER + token);
            }
            if (null != sysTenantNo) {
                headers.put(InterceptorConstants.META_KEY_SYS_TENANT_NO, sysTenantNo + "");
            }

            if (null != wsVer) {
                headers.put(InterceptorConstants.META_KEY_WS_VER, wsVer);
            }
            if (null != appVersion) {
                headers.put(InterceptorConstants.META_KEY_APP_VERSION, appVersion);
            }

            Logger.d("head: " + headers);
        }
        super.start(new WsClientCallListener(responseListener), headers);
    }

    public interface Provider {
        String token();

        Integer sysTenantNo();

        String wsVer();

        String appVersion();
    }
}
